<?php

class OneChoice extends Content implements IContentExtra
{
    /**
     * array(
     *      'id'=> xxxx,
     *      'title' => xxxx,
     *      'text' => xxxx,
     * )
     * @var array
     */
    public $choices=array();
    
    public $explain;
    
    public function rules()
    {
        return array_merge(parent::rules(), array(
            array('explain, choices', 'safe'),
        ));
    }
    
    public function behaviors()
    {
        return array(
            'embeddedSubjects'=>array(
                'class'=>'common.extensions.YiiMongoDbSuite.extra.EEmbeddedArraysBehavior',
                'arrayPropertyName'=>'choices',
                'arrayDocClassName'=>'Choice'
            ),
        );
    }
    
    static public function getTypeName()
    {
        return 'one_choice';
    }
    
    static public function getInstanceByAttributes($attributes = null, $runSetAttributes = true)
    {
        $model = new self;
        if($runSetAttributes)
            $model->setAttributes($attributes);

        return $model;
    }
    
    public function getDisplayChoices()
    {
        return $this->choices;
    }
    
    public function getDisplaySummary()
    {
        return $this->text;
    }
    
    /**
     * 
     * @param type $id
     * @return boolean
     */
    public function check($id)
    {
        $choice = $this->getChoiceById($id);
        
        if( ! ($choice instanceof Choice))
            return false;
        
        return (bool)$choice->getAnswer();
    }
    
    public function getChoiceById($id)
    {
        if(empty($id))
            return false;
        
        if(empty($this->choices))
            return false;
        
        foreach($this->choices as $choice)
        {
            if( ! ($choice instanceof Choice))
                continue;

            if($choice->getId() === $id)
                return $choice;
        }
        
        return false;
    }
    
    public function getExplain()
    {
        return $this->explain;
    }
    
    public function setChoices(array $choices)
    {
        $this->choices = $choices;
    }
}

